<template>
  <div class="room-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>房间管理</span>
          <div style="display: flex; gap: 15px; align-items: center">
            <el-select
              v-model="selectedRoomType"
              placeholder="选择房间类型"
              style="width: 150px"
              multiple
              collapse-tags
              collapse-tags-tooltip
            >
              <el-option
                v-for="type in roomTypes"
                :key="type.typeId"
                :label="type.typeName"
                :value="type.typeId"
              />
            </el-select>
            <el-select
              v-model="selectedStatus"
              placeholder="选择房间状态"
              style="width: 150px"
            >
              <el-option label="全部" :value="null" />
              <el-option
                v-for="status in Object.values(RoomStatus)"
                :key="status"
                :label="getStatusLabel(status)"
                :value="status"
              />
            </el-select>
            <el-button type="primary" @click="openDialog">添加房间</el-button>
            <el-button
              type="warning"
              :disabled="!selectedRows.length"
              style="margin-left: 0px"
              @click="openBatchUpdateDialog"
              >批量更新</el-button
            >
            <el-button
              type="success"
              :disabled="!selectedRows.length"
              @click="handleCheckIn"
              >登记入住</el-button
            >
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="filteredTableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="roomId" label="ID" width="50" />
        <el-table-column prop="roomNumber" label="房间号" width="80" />
        <el-table-column prop="roomTypeId" label="房间类型" width="120">
          <template #default="scope">
            {{ getRoomTypeName(scope.row.roomTypeId) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
        v-model="batchUpdateDialogVisible"
        title="批量更新房间信息"
        width="500px"
      >
        <el-form
          :model="batchUpdateForm"
          label-width="auto"
          style="max-width: 400px"
        >
          <el-form-item label="房间类型" prop="roomTypeId">
            <el-select
              v-model="batchUpdateForm.roomTypeId"
              placeholder="请选择房间类型"
              clearable
            >
              <el-option
                v-for="type in roomTypes"
                :key="type.typeId"
                :label="type.typeName"
                :value="type.typeId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="batchUpdateForm.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option
                v-for="status in Object.values(RoomStatus)"
                :key="status"
                :label="getStatusLabel(status)"
                :value="status"
              />
            </el-select>
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="batchUpdateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchUpdate"
            >确认更新</el-button
          >
        </template>
      </el-dialog>
      <el-dialog
        v-model="dialogVisible"
        :title="isEditing ? '编辑房间' : '添加房间'"
        width="500px"
      >
        <el-form :model="form" label-width="auto" style="max-width: 400px">
          <el-form-item label="房间号" prop="roomNumber">
            <el-input v-model="form.roomNumber" placeholder="请输入房间号" />
          </el-form-item>
          <el-form-item label="房间类型" prop="roomTypeId">
            <el-select v-model="form.roomTypeId" placeholder="请选择房间类型">
              <el-option
                v-for="type in roomTypes"
                :key="type.typeId"
                :label="type.typeName"
                :value="type.typeId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态">
              <el-option
                v-for="status in Object.values(RoomStatus)"
                :key="status"
                :label="getStatusLabel(status)"
                :value="status"
              />
            </el-select>
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">{{
            isEditing ? "保存修改" : "提交"
          }}</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { Room, RoomType } from "@/api/room";
import {
  getRoomList,
  updateRoom,
  createRoom,
  deleteRoom,
  getRoomTypeList,
  RoomStatus,
  batchUpdateRoom
} from "@/api/room";
import { useRouter } from "vue-router";

defineOptions({
  name: "RoomDetail"
});

const tableData = ref<Room[]>([]);
const roomTypes = ref<RoomType[]>([]);
const loading = ref(true);
const dialogVisible = ref(false);
const isEditing = ref(false);
const selectedRoomType = ref<number[]>([]);
const selectedStatus = ref<RoomStatus | null>(null);

const filteredTableData = computed(() => {
  return tableData.value.filter(room => {
    const matchType =
      selectedRoomType.value.length === 0 ||
      selectedRoomType.value.includes(room.roomTypeId);
    const matchStatus =
      selectedStatus.value === null || room.status === selectedStatus.value;
    return matchType && matchStatus;
  });
});

const form = ref<Room>({
  roomId: null,
  roomTypeId: null,
  roomNumber: "",
  status: RoomStatus.AVALIABLE,
  isDeleted: false
});

const getRoomTypeName = (typeId: number) => {
  const roomType = roomTypes.value.find(type => type.typeId === typeId);
  return roomType ? roomType.typeName : "未知类型";
};

const fetchRoomTypes = async () => {
  try {
    const data = await getRoomTypeList();
    if (data.code === 200) {
      roomTypes.value = data.data;
    } else {
      ElMessage.error(data.msg || "获取房间类型列表失败");
    }
  } catch (error) {
    ElMessage.error("获取房间类型列表失败");
    console.error(error);
  }
};

const getStatusLabel = (status: RoomStatus) => {
  const statusMap = {
    [RoomStatus.AVALIABLE]: "可用",
    [RoomStatus.BOOKED]: "已预订",
    [RoomStatus.CHECKED_IN]: "已入住",
    [RoomStatus.CHECKED_OUT]: "已退房",
    [RoomStatus.CLEANING]: "清洁中",
    [RoomStatus.MAINTENANCE]: "维护中",
    [RoomStatus.VACANT]: "空置"
  };
  return statusMap[status];
};

type TagType = "success" | "warning" | "info" | "primary" | "danger";

const getStatusType = (status: RoomStatus): TagType => {
  const typeMap: Record<RoomStatus, TagType> = {
    [RoomStatus.AVALIABLE]: "success",
    [RoomStatus.BOOKED]: "warning",
    [RoomStatus.CHECKED_IN]: "info",
    [RoomStatus.CHECKED_OUT]: "info",
    [RoomStatus.CLEANING]: "warning",
    [RoomStatus.MAINTENANCE]: "danger",
    [RoomStatus.VACANT]: "info"
  };
  return typeMap[status];
};

const fetchRooms = async () => {
  try {
    const data = await getRoomList();
    if (data.code === 200) {
      tableData.value = data.data;
    } else {
      ElMessage.error(data.msg || "获取房间列表失败");
    }
  } catch (error) {
    ElMessage.error("获取房间列表失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const openDialog = () => {
  isEditing.value = false;
  form.value = {
    roomId: null,
    roomTypeId: null,
    roomNumber: "",
    status: RoomStatus.AVALIABLE,
    isDeleted: false
  };
  dialogVisible.value = true;
};

const handleEdit = (row: Room) => {
  isEditing.value = true;
  Object.assign(form.value, row);
  dialogVisible.value = true;
};

const handleSubmit = async () => {
  try {
    if (isEditing.value) {
      const response = await updateRoom(form.value);
      if (response.code === 200) {
        const index = tableData.value.findIndex(
          item => item.roomId === form.value.roomId
        );
        if (index !== -1) {
          Object.assign(tableData.value[index], form.value);
        }
        ElMessage.success("修改成功");
      } else {
        ElMessage.error(response.msg || "修改失败");
        return;
      }
    } else {
      const response = await createRoom([parseInt(form.value.roomNumber)]);
      if (response.code === 200) {
        await fetchRooms();
        ElMessage.success("创建成功");
      } else {
        ElMessage.error(response.msg || "创建失败");
        return;
      }
    }
    dialogVisible.value = false;
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  }
};

const handleDelete = (row: Room) => {
  ElMessageBox.confirm("确定要删除这个房间吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        const response = await deleteRoom([row.roomNumber]);
        if (response.code === 200) {
          tableData.value = tableData.value.filter(
            item => item.roomNumber !== row.roomNumber
          );
          ElMessage.success("删除成功");
        } else {
          ElMessage.error(response.msg || "删除失败");
        }
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败，请稍后重试");
      }
    })
    .catch(() => {
      ElMessage.info("删除取消");
    });
};

onMounted(() => {
  fetchRoomTypes();
  fetchRooms();
});

const selectedRows = ref<Room[]>([]);
const batchUpdateDialogVisible = ref(false);
const batchUpdateForm = ref({
  status: null,
  roomTypeId: null
});

const handleSelectionChange = (rows: Room[]) => {
  selectedRows.value = rows;
};

const openBatchUpdateDialog = () => {
  batchUpdateDialogVisible.value = true;
};

const handleBatchUpdate = async () => {
  try {
    if (!batchUpdateForm.value.status && !batchUpdateForm.value.roomTypeId) {
      ElMessage.warning("请至少选择一项要更新的内容");
      return;
    }
    const updatedRooms = selectedRows.value.map(room => ({
      ...room,
      ...(batchUpdateForm.value.status !== null && {
        status: batchUpdateForm.value.status
      }),
      ...(batchUpdateForm.value.roomTypeId !== null && {
        roomTypeId: batchUpdateForm.value.roomTypeId
      })
    }));
    const response = await batchUpdateRoom(updatedRooms);
    if (response.code === 200) {
      updatedRooms.forEach(updatedRoom => {
        const index = tableData.value.findIndex(
          item => item.roomId === updatedRoom.roomId
        );
        if (index !== -1) {
          Object.assign(tableData.value[index], updatedRoom);
        }
      });
      ElMessage.success("批量更新成功");
      batchUpdateDialogVisible.value = false;
    } else {
      ElMessage.error(response.msg || "批量更新失败");
    }
  } catch (error) {
    console.error("批量更新失败:", error);
    ElMessage.error("批量更新失败，请稍后重试");
  }
};

const router = useRouter();

const handleCheckIn = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择需要登记入住的房间");
    return;
  }

  const invalidRooms = selectedRows.value.filter(
    room => room.status !== RoomStatus.AVALIABLE
  );

  if (invalidRooms.length > 0) {
    ElMessage.error(
      `房间 ${invalidRooms.map(room => room.roomNumber).join(", ")} 当前不可用，请选择可用状态的房间`
    );
    return;
  }

  const roomNumbers = selectedRows.value.map(room => room.roomNumber);

  router.push({
    path: "/checkIn/index",
    query: {
      roomNumbers: roomNumbers.join(",")
    }
  });
};
</script>

<style scoped>
.room-container {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
